<template>
  <div>
    <el-dialog :visible.sync="dialogOpen" :title="title" width="50%" center :close-on-click-modal="false"
               @close="handleDialogClose" top="50px" v-if="dialogOpen">
      <el-form v-loading="loadingDialog"
               element-loading-text="拼命加载中"
               element-loading-spinner="el-icon-loading"
               element-loading-background="rgba(0, 0, 0, 0.8)">
        <div style="color: red;margin-bottom: 10px;position: relative">
          <p>1.DXF文件上传需要将所有[块]全部炸开</p>
          <p>2.[CAD辅助识别]功能作为图片识别的二次检查</p>
          <p>3.如果使用CAD辅助识别，请同时上传[图片][DXF文件]</p>
          <p>4.此功能上线作为测试CAD识别的准确性，如果准确性没问题，后期会下架图片识别，全部使用CAD识别</p>
        </div>
        <div style="display: flex;justify-content: space-around;margin-bottom: 10px">
          <p></p>
          <p>图片识别：</p>
          <p>CAD辅助识别:</p>
          <p style="width: 150px"></p>
        </div>
        <el-form-item label="转化图" style="width: 100%;" label-width="120px">
          <div style="display: flex;justify-content: space-around">
            <Uploader :title="'上传图片'" v-model="fileList" :disabled="active !== null && active !== 1"
                      @addStatus="receiveData"/>
            <Uploader :title="'上传DXF文件'" v-model="dxfList" :disabled="active !== null && active !== 1"
                      @click.native="handleClick(1)" @addStatus="receiveData"/>
            <el-button @click="handleUpload('type1')" size="small" style="width: 80px;height: 35px" type="primary">
              手动输入
            </el-button>
          </div>
          <div style="max-height: 200px;overflow-y: scroll"><p v-for="item in shelvesJsonArray"><span style="margin-right: 20px
">{{ item.id }}</span> <span style="color: #F56C6C">x{{ item.count }}</span></p></div>
        </el-form-item>
        <el-form-item label="仓储架图" style="width: 100%" label-width="120px">
          <div style="display: flex;justify-content: space-around">
            <Uploader :title="'上传图片'" v-model="fileList2" :disabled="active !== null && active !== 2"
                      @addStatus="receiveData"/>
            <Uploader :title="'上传DXF文件'" v-model="dxfList2" :disabled="active !== null && active !== 2"
                      @click.native="handleClick(2)" @addStatus="receiveData"/>
            <el-button @click="handleUpload('type2')" size="small" style="width: 80px;height: 35px" type="primary">
              手动输入
            </el-button>
          </div>
          <div style="max-height: 200px;overflow-y: scroll"><p v-for="item in storageJsonArray"><span style="margin-right: 20px
">{{ item.id }}</span> <span style="color: #F56C6C">x{{ item.count }}</span></p></div>
        </el-form-item>
        <!-- <el-form-item label="仓储报价图" style="width: 100%">
          <Uploader v-model="fileList3" />
        </el-form-item> -->
        <el-form-item label="营业报价图" style="width: 100%" label-width="120px">
          <div style="display: flex;justify-content: space-around">
            <Uploader :title="'上传图片'" v-model="fileList3" :disabled="active !== null && active !== 3"
                      @addStatus="receiveData"/>
            <Uploader :title="'上传DXF文件'" v-model="dxfList3" :disabled="active !== null && active !== 3"
                      @click.native="handleClick(3)" @addStatus="receiveData"/>
            <el-button @click="handleUpload('type3')" size="small" style="width: 80px;height: 35px" type="primary">
              手动输入
            </el-button>
          </div>
          <div style="max-height: 200px;overflow-y: scroll"><p v-for="item in goodsOfferJsonArray"><span style="margin-right: 20px
">{{ item.id }}</span> <span style="color: #F56C6C">x{{ item.count }}</span></p></div>
        </el-form-item>
        <el-form-item label="仓储报价图" style="width: 100%" label-width="120px">
          <div style="display: flex;justify-content: space-around">
            <Uploader :title="'上传图片'" v-model="fileList4" :disabled="active !== null && active !== 4"
                      @addStatus="receiveData"/>
            <Uploader :title="'上传DXF文件'" v-model="dxfList4" :disabled="active !== null && active !== 4"
                      @click.native="handleClick(4)" @addStatus="receiveData"/>
            <el-button @click="handleUpload('type4')" size="small" style="width: 80px;height: 35px" type="primary">
              手动输入
            </el-button>
          </div>
          <div style="max-height: 200px;overflow-y: scroll"><p v-for="item in storageOfferJsonArray"><span style="margin-right: 20px
">{{ item.id }}</span> <span style="color: #F56C6C">x{{ item.count }}</span></p></div>
        </el-form-item>
        <el-progress
            v-if="loading"
            :percentage="progress"
            :status="progressStatus"
            :stroke-width="16"
            style="margin: 20px 0;"
            :show-text="true"
        ></el-progress>
      </el-form>
      <span slot="footer">
         <el-button type="primary" @click="onConfirm" v-preventReClick>图片解析</el-button>
            <el-button @click="handleDialogClose">取 消</el-button>
            <el-button type="warning" @click="handleSubmit" v-preventReClick>手动解析</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="handleUploadDialog" append-to-body width="40%" title="手动增加套件">
      <el-button size="small" type="primary" style="margin: 0 80px 5px 80px;"
                 @click="pushProduceList">增加套件
      </el-button>

      <div style="display: flex;align-items: center;margin-top: 10px" v-for="(item,index) in addForm.addMaterialsList"
           :key="'addMaterialsList'+index">
        <el-select v-if="type=='type1'||type=='type2'" v-model="item.id" remote filterable
                   :remote-method="changeProduce"
                   placeholder="请选择" style="width: 350px;margin-left: 80px" size="small">
          <el-option v-for="(item,index) in produceList" :key="index"
                     :value="item.code"
                     :label="item.name">
          </el-option>
        </el-select>
        <el-select v-if="type=='type3'||type=='type4'" v-model="item.id" remote filterable
                   :remote-method="changeProduce2"
                   placeholder="请选择" style="width: 350px;margin-left: 80px" size="small">
          <el-option v-for="(item,index) in produceList2" :key="index"
                     :value="item.code"
                     :label="item.name">
          </el-option>
        </el-select>
        <el-input-number style="margin-left:10px" v-model="item.count" :min="0"
                         size="small"></el-input-number>
        <el-link style="font-size: 12px;width: 80px"
                 @click="deleteProduce(addForm.addMaterialsList,index)">删除
        </el-link>
      </div>
      <span slot="footer">
        <el-button style="background-color:#409EFF;color: #eeeeee" @click="_submit">提 交</el-button>
        <el-button style="background-color:#eee;color: #666" @click="handleUploadDialog=false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="compareDialog" append-to-body width="40%" :close-on-click-modal="false" title="选择差异数量">
      <div v-for="item in differenceList" style="margin: 10px 0">
        <span v-if="item.flag==2">未知编码：{{ item.code }} <span style="margin-left: 48px">图片：{{
            item.count1 || 0
          }}</span><span style="margin-left: 60px">dxf：{{ item.count2 || 0 }}</span></span>
        <span v-if="item.flag==1">差异编码：{{ item.code }}</span>
        <span v-if="item.flag!=2" style="margin-left: 30px"> <el-radio v-model="item.correctCount"
                                                                       label="1">图片：{{ item.count1 }}</el-radio>
       <el-radio-group v-model="item.correctCount">
<el-radio label="2">dxf： {{ item.count2 }}</el-radio>
  <el-radio label="3">
    <span>其他</span>
    <el-input
        v-if="item.correctCount === '3'"
        style="width: 200px; margin-left: 8px"
        size="small"
        v-model="item.count3"
        placeholder="输入其他正确数量"
    />
  </el-radio>
</el-radio-group></span>
      </div>
      <span slot="footer"><el-button type="primary" size="small" @click="compareComfirm(differenceList)">确认</el-button></span>
    </el-dialog>
  </div>
</template>

<script>
import uploader from "../../../components/Element/Uploader.vue";

export default {
  name: "CADupload",
  components: {
    uploader
  },
  data() {
    return {
      dialogOpen: false,
      row: {},
      title: "",
      labelPosition: "left",
      differenceList: [],
      compareDialog: false,
      fileList: '',
      fileList2: '',
      fileList3: '',
      fileList4: '',
      dxfList: '',
      loadingDialog: false,
      dxfList2: '',
      dxfList3: '',
      dxfList4: '',
      active: null, // 记录点击的按钮编号
      shelvesJsonArray: [],
      storageJsonArray: [],
      goodsOfferJsonArray: [],
      storageOfferJsonArray: [],
      form: {},
      type: "",
      differenceType: "",
      handleUploadDialog: false,
      produceList: [],
      produceList2: [],
      loading: false,       // 控制进度条显示
      progress: 0,          // 进度百分比
      progressStatus: null,   // success / exception
      addForm: {
        addMaterialsList: [{
          norms: "",
          count: 0
        }],
      },
    }
  },
  methods: {
    handleOpen(val) {
      this.row = val
      this.title = `CAD上传-${val.storeName}`
      this.dialogOpen = true
    },
    handleClick(num) {
      this.active = num
    },
    receiveData(val) {
      if (val == 1) this.loadingDialog = true
      if (val == 2) this.loadingDialog = false
    },
    async onConfirm(form) {
      this.loading = true
      this.progress = 0
      this.progressStatus = null // 进度条状态
      let timer = null
      // 开始模拟进度递增
      timer = setInterval(() => {
        if (this.progress < 90) {
          this.progress += Math.floor(Math.random() * 5) + 1 // 每次递增 1~5%
        }
      }, 200)

      try {
        const {
          row,
          fileList, fileList2, fileList3, fileList4,
          dxfList, dxfList2, dxfList3, dxfList4
        } = this
        const {id, orderType} = row
        // 设置表单数据
        form.id = id
        form.orderType = orderType
        form.cadImg = fileList
        form.storageImg = fileList2
        form.goodsOfferImg = fileList3
        form.storageOfferImg = fileList4
        form.cadDxf = dxfList
        form.storageDxf = dxfList2
        form.goodsOfferDxf = dxfList3
        form.storageOfferDxf = dxfList4

        // 请求接口
        const res = await this.$api.newCadParse(form)

        // 接口返回后，立即让进度条完成
        this.progress = 100
        this.progressStatus = 'success'
        clearInterval(timer)

        // 小延迟让动画自然结束
        setTimeout(() => {
          if (res.code?.length === 0 && res.listDifference?.length === 0) {
            this.$confirm('解析完成! 图片和 CAD 解析结果一致！', '成功', {
              confirmButtonText: '确定',
              type: 'success',
              showCancelButton: false,
            }).then(() => {
              this.dialogVisible = false
            }).catch(() => {
            })
          } else if (Array.isArray(res.listDifference) && res.listDifference.length > 0) {
            this.differenceList = res.listDifference
            this.differenceType = res.type
            this.compareDialog = true
          } else if (res.code?.length === 0 && res.listDifference == null) {
            this.$message.success('上传成功！')
          }
          this.loading = false
        }, 800)
      } catch (error) {
        console.error('CAD 解析失败:', error)
        clearInterval(timer)
        this.progressStatus = 'exception'
        this.$message.error('解析过程中出现错误，请稍后再试')
        this.loading = false
      } finally {
        clearInterval(timer)
      }
    },
    handleSubmit(form) {
      const {row} = this;
      const {id, orderType} = row;
      form.id = id;
      form.orderType = orderType;
      form.shelvesJsonArray = this.shelvesJsonArray
      form.storageJsonArray = this.storageJsonArray
      form.goodsOfferJsonArray = this.goodsOfferJsonArray
      form.storageOfferJsonArray = this.storageOfferJsonArray
      this.$api.newCadParse2(form).then(this.submitDoneMsg)
    },
    handleDialogClose() {
      this.dialogOpen = false
      this.loadingDialog = false
      this.fileList = '';
      this.fileList2 = '';
      this.fileList3 = '';
      this.fileList4 = '';
      this.dxfList = '';
      this.dxfList2 = '';
      this.dxfList3 = '';
      this.dxfList4 = '';
      this.shelvesJsonArray = [];
      this.storageOfferJsonArray = [];
      this.storageJsonArray = [];
      this.goodsOfferJsonArray = [];
      this.active = null
      this.loading = false
      this.$emit('addStatus', 1)
    },
    handleUpload(type) {
      this.type = type
      this.handleUploadDialog = true
      const map = {
        type1: 'shelvesJsonArray',
        type2: 'storageJsonArray',
        type3: 'goodsOfferJsonArray',
        type4: 'storageOfferJsonArray',
      };
      const key = map[this.type];
      if (key) {
        this.addForm.addMaterialsList = this[key];
      }
    },
    pushProduceList() {
      this.addForm.addMaterialsList = [...this.addForm.addMaterialsList, {
        norms: "",
        count: 0
      }]
    },
    deleteProduce(list, index) {
      list.splice(index, 1)
    },
    changeProduce(val) {
      this.$api.orderGetDirectoryVo({name: val}).then(res => {
        this.produceList = res
      })
    },
    changeProduce2(val) {
      this.$api.orderGetQuotationList({name: val}).then(res => {
        this.produceList2 = res
      })
    },
    _submit() {
      const idSet = new Set();
      const hasEmptyCount = this.addForm.addMaterialsList.some((e, i) => {
        delete e.norms
        if (!e.count || e.count == 0) {
          this.$message.warning('第' + (i + 1) + '行没有填写数量！');
          return true;
        }
        // id 重复
        if (idSet.has(e.id)) {
          this.$message.warning('第' + (i + 1) + '行的套件重复添加！');
          return true;
        } else {
          idSet.add(e.id);
        }
        return false;
      });
      if (hasEmptyCount) return;
      this.handleUploadDialog = false;
      const map = {
        type1: 'shelvesJsonArray',
        type2: 'storageJsonArray',
        type3: 'goodsOfferJsonArray',
        type4: 'storageOfferJsonArray',
      };
      const key = map[this.type];
      this[key] = this.addForm.addMaterialsList;
    },
    compareComfirm(val) {
      this.$message.success('请稍后..')
      val.forEach(el => {
        if (el.correctCount == 1) el.count3 = el.count1
        if (el.correctCount == 2) el.count3 = el.count2
      })
      const {id} = this.row
      const data = {
        orderId: id,
        type: this.differenceType,
        listDifference: val
      }
      for (const [index, el] of data.listDifference.entries()) {
        if (el.correctCount == null && el.flag == 1) {
          this.$message.error(`第${index + 1}行未选择正确的编码分析数量，请重新选择或输入对应的数量！`)
          return
        }
      }
      this.$api.newCadUpdateCadAnalysis(data).then(res => {
        if (res == 1) {
          this.$message.success('成功！')
          this.compareDialog = false
          this.submitDoneMsg()
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

</style>